/**  
 * GalleryAdapter.java
 * @version 1.0
 * @author Haven
 * @createTime 2011-12-9 濞戯拷鎷烽敓锟�:04:34
 */
package com.cn.onetrip.rorate3d;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;

import com.cn.onetrip.activity.R;
import com.cn.onetrip.objects.AtlasObj;
import com.cn.onetrip.untility.HTTPUrl;
import com.cn.onetrip.untility.ImageUtils;
import com.cn.onetrip.untility.MD5;

public class ScenicGalleryAdapter extends BaseAdapter {

	private static Context context;
	public static HashMap<String, Bitmap> imagesCache = new HashMap<String, Bitmap>();

	private LayoutInflater mInflater;
	int mGalleryItemBackground;
	private Handler mHandler;
	private String[] mTexts, imageUrls;
	private static int errorCount = 0;

	public ScenicGalleryAdapter(Context context, AtlasObj atlasObj) {
		this.context = context;
	}

	public ScenicGalleryAdapter(Context c, Handler handler, String[] ImageUrl,
			String[] text) {
		this.context = c;
		mInflater = LayoutInflater.from(c);
		this.mHandler = handler;
		this.imageUrls = ImageUrl;
		this.mTexts = text;
	}

	@Override
	public int getCount() {
		return Integer.MAX_VALUE;
		// return imageUrls.length;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView != null) {
			Log.w("getView", "convertView != null");
			return convertView;
		} else {
			if (position < 0) {
				position = position + imageUrls.length;
			} else if (position > imageUrls.length - 1) {
				position = position % imageUrls.length;
			}
			return getMyImageView(position, 1);

		}
	}

	public ScaleImageView getMyImageView(int position, int sampleSize) {
		Bitmap bmp = null;
		try {
			// bmp = imagesCache.get(atlasObj.picList.get(position
			// % atlasObj.picList.size()).imageUrl);

			bmp = imagesCache.get(imageUrls[position % imageUrls.length]);
		} catch (OutOfMemoryError e) {
			// TODO: handle exception
			try {
				bmp = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.default_image_big);
			} catch (OutOfMemoryError err2) {
				// TODO: handle exception
				err2.printStackTrace();

			}
		}
		if (bmp == null) {
			try {
				bmp = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.default_image_big);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}

		}
		ScaleImageView view = new ScaleImageView(context, bmp.getWidth(),
				bmp.getHeight());
		view.setLayoutParams(new Gallery.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		view.setImageBitmap(bmp);
		return view;
	}

	public static Bitmap getBitmap(String url) {
		URL myFileURL;
		Bitmap bitmap = null;
		File file = new File(url);
		if (imagesCache.containsKey(url)) {
			bitmap = imagesCache.get(url);
			if (bitmap != null) {
				return bitmap;
			} else {
				imagesCache.remove(url);
				getBitmap(url);
			}
		}
		if (file.exists()) {
			try {
				bitmap = ImageUtils.getBitmap(file, 1);
			} catch (OutOfMemoryError e) {
				// TODO: handle exception
				return null;
			}
			imagesCache.put(url, bitmap);
			return bitmap;
		}
		try {
			myFileURL = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myFileURL
					.openConnection();
			conn.setConnectTimeout(6000);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// conn.connect();
			InputStream is = conn.getInputStream();
			try {
				bitmap = BitmapFactory.decodeStream(is);
			} catch (OutOfMemoryError e) {
				// TODO: handle exception
				return null;
			}
			is.close();
			imagesCache.put(url, bitmap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	public static Bitmap loadImageFromUrl(String url) throws IOException {
		if (url == null || url.length() == 0)
			return null;
		Bitmap bitmap = null;
		System.out.println(url);

		if (imagesCache.containsKey(url)) {
			bitmap = imagesCache.get(url);
			if (bitmap != null) {
				return bitmap;
			} else {
				imagesCache.remove(url);
			}
		}
		File file = new File(url);
		if (file.exists()) {
			try {
				bitmap = ImageUtils.getBitmap(file, 1);
			} catch (OutOfMemoryError e) {
				// TODO: handle exception
				return null;
			}
			imagesCache.put(url, bitmap);
			return bitmap;
		} else {
			File f = new File(HTTPUrl.ImageCacheFloder + "/" + MD5.getMD5(url));
			if (f.exists()) {
				FileInputStream fis = new FileInputStream(f);
				try {
					bitmap = BitmapFactory.decodeStream(fis);
					if (bitmap != null) {
						imagesCache.put(url, bitmap);
						fis.close();
						System.gc();
						return bitmap;
					} else {
						if (errorCount < 3) {
							errorCount++;
							f.delete();
							loadImageFromUrl(url);
						} else {
							errorCount = 0;
							return bitmap;
						}
					}
				} catch (OutOfMemoryError err) {
					// TODO: handle exception
					fis.close();
					System.gc();
					Bitmap b = null;
					try {
						b = BitmapFactory.decodeResource(
								context.getResources(),
								R.drawable.default_image_big);
						return b;
					} catch (OutOfMemoryError err2) {
						return null;
					}
				}
			} else {
				URL m = new URL(url);
				InputStream i = (InputStream) m.getContent();
				DataInputStream in = new DataInputStream(i);
				FileOutputStream out = new FileOutputStream(f);

				byte[] buffer = new byte[1024];
				int byteread = 0;
				while ((byteread = in.read(buffer)) != -1) {
					out.write(buffer, 0, byteread);
				}
				in.close();
				out.close();
				i.close();
				System.gc();
				// Drawable d = Drawable.createFromStream(i, "src");
				return loadImageFromUrl(url);
			}
		}
		return bitmap;
	}
}
